﻿// ***********************************************************************
// Assembly         : OSS.BIM
// Author           : tianteng
// Created          : 03-16-2018
//
// Last Modified By : tianteng
// Last Modified On : 03-16-2018
// ***********************************************************************
// <copyright file="AddModelCmd.cs" company="北京智帆高科科技有限公司">
//     Copyright ©  2017
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Osg;
using OSS.BIM.Business;
using OSS.BIM.Business.Utility;
using ZFGK.Addins;
using ZFGK.Delegates;
using ZFGK.IO;
using ZFGK.osgEarth.Utility;
using ZFGK.OSG.Utility;
using ZFGK.Utility;
using ZFGK.DevExprss.Forms;
using ZFGK.osgEarth.UI;
using ZFGK.WinForms.Utility;
using OSS.BIM.Model;
using OSS.BIM.SceneManage;
using OSS.BIM.UI.PropertyGrids;
using OSS.BIM.Utility;
using ZfPlatform.Utility;

namespace OSS.BIM.Commands.GroupModelCmds
{
    /// <summary>
    /// Class AddModelCmd.
    /// </summary>
    /// <seealso cref="ZFGK.Addins.IExtendCommand" />
    public class GroupModeAddCmd : IExtendCommand
    {
        /// <summary>
        /// Executes the specified command data.
        /// </summary>
        /// <param name="cmdData">The command data.</param>
        /// <param name="message">The message.</param>
        /// <returns>CmdResult.</returns>
        public CmdResult Execute(ExtendCmdData cmdData, ref string message)
        {
//             if (!PermissionApp.CurUser.CheckUser())
//             {
//                 return CmdResult.Cancel;
            //             }
            var form = cmdData.ViewForm as OsgEarthViewForm;
            var osgEarthViewCtrl = form.OsgEarthViewCtrl;
            var actionUtility = osgEarthViewCtrl.ActionUtility;
            var userGroup = cmdData.Tag as ModelGrope;
            if (userGroup == null)
                userGroup = CurUserGroup.Instance.ModelGrope;
            if (userGroup == null)
            {
                ZfMessageUtil.ShowError("当前分组为空，请设置!", "错误");
                return CmdResult.Cancel;
            }

            string srcFileName;
            if (!DialogUtil.OpenOSG(out srcFileName))
                return CmdResult.Cancel;

            bool bTemp = false;
//             if (Path.GetExtension(srcFileName).ToLower().CompareTo(".ive") != 0)
//             {
//                 DirectoryUtil.AssertDirExist(Zf3DConfigUtil.TempModelPath());
//                 // 先把模型放到临时模型目录
//                 var tempNode = osgDB.osgDB.readNodeFile(srcFileName);
//                 string destFileName = Path.Combine(Zf3DConfigUtil.TempModelPath(),
//                     Path.GetFileNameWithoutExtension(srcFileName) + ".ive");
//                 // 有可能材质什么没在osgt文件里面
//                 osgDB.osgDB.writeNodeFile(tempNode, destFileName);
//                 srcFileName = destFileName;
//                 bTemp = true;
//             }

            string hashCode = FileUtil.GetHashCode(srcFileName);
            var node = ZfModelCache.GetNode(srcFileName, hashCode);
            if (!node.IsValid)
            {
                ZfMessageUtil.ShowError("模型读取失败!");
                return CmdResult.Cancel;
            }


            ModelElement userModel = ZfCacheUtil.valueCache.LaodCache<ModelElement>();
            if (userModel == null)
            {
                userModel = new ModelElement();
                // 给初始值
                userModel.Scale = new Vec3d(0.01, 0.01, 0.01).ToString();
            }
            userModel.Name = Path.GetFileNameWithoutExtension(srcFileName);
            var userModelBinding = new ModelInfoBinding(userModel);

            var propertyGridAddEditForm = new DvPropertyGridEditForm("添加模型", userModelBinding);
            propertyGridAddEditForm.Icon = form.Icon;
            propertyGridAddEditForm.ValueValidated += delegate(object sender, ValueValidatedArgs args)
            {
                userModelBinding.Name = userModelBinding.Name.Trim();
                if (string.IsNullOrEmpty(userModelBinding.Name))
                {
                    args.ErrorMessage.AppendLine("模型名称不能为空!");
                    return false;
                }
                if (userModelBinding.Scale.x <= 0 || userModelBinding.Scale.y <= 0 || userModelBinding.Scale.z <= 0)
                {
                    args.ErrorMessage.AppendLine("缩放必须为正数!");
                    return false;
                }
                // 缓存记忆值
                ZfCacheUtil.valueCache.SaveCache(userModel);
                return true;
            };
            if (propertyGridAddEditForm.ShowDialog(cmdData.ViewForm as OsgEarthViewForm) != DialogResult.OK)
                return CmdResult.Cancel;

            Matrixd scaleMat = Matrixd.scale(userModel.Scale.ParseVec3d());
            MatrixTransform mtf = new MatrixTransform(scaleMat);
            mtf.addChild(node);

            Vec3d mapPt = null, mapPt2 = null;
            // 选择插入点
            if (!actionUtility.PickEarthPoint("放置模型", mtf, out mapPt))
                return CmdResult.Cancel;
            if (!actionUtility.PickEarthPointLastex("旋转模型", mapPt, mtf, out mapPt2))
                return CmdResult.Cancel;

            // 模型类型表
            var userModelFile = ModelFileDbUtil.GetAtByFingerprint(hashCode);
            if (userModelFile == null)
            {
                userModelFile = new ModelFile();
                userModelFile.Name = Path.GetFileNameWithoutExtension(srcFileName);
                userModelFile.Extension = Path.GetExtension(srcFileName);
                userModelFile.Fingerprint = hashCode;
                if (ModelFileDbUtil.Insert(userModelFile))
                {
                    userModelFile = ModelFileDbUtil.GetLast(1).First();

                    //拷贝模型到文件夹
                    DirectoryUtil.EnsureDirExist(BmConfigUtil.ModelsPath);
                    string destFileName = userModelFile.GetNodePath();
                    if (bTemp)
                    {
                        File.Move(srcFileName, destFileName);
                    }
                    else
                    {
                        File.Copy(srcFileName, destFileName, true);
                    }
                }
            }

            double rotation = mapPt.Rotation(mapPt2); //旋转角度 弧度
            userModel.SetLocation(mapPt);                   //设置插入点位置
            userModel.Rotation = rotation;
            userModel.ModelGropeId = userGroup.ModelGropeId;
            userModel.ModelElementId = userModelFile.ModelFileId;
            userModel.ModelType = (int)ModelType.LoadFile;
            userModel.AttachAll();
            if (ModelElementDbUtil.Insert(userModel))
            {
                ZfMessageUtil.ShowError("更新数据库失败!", "数据库错误");
                return CmdResult.Cancel;
            }

            // 获取最新添加的数据
            userModel = ModelElementDbUtil.GetLast(1).First();
            // 
            userModel.AddOrUpdateTreeListNode();
            osgEarthViewCtrl.OsgEarthObj.AddOrReplaceModel(userModel);

            return CmdResult.Succeed;
        }
    }
}
